package com.hk.core.autoconfigure.error;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;

/**
 * <pre>
 *
 * 错误视图解析， 前后端分离，Vue 使用 hash 模式
 *  当用户手动在浏览器输入不正确的地址时，重定向到 vue 的 404页面
 *  当系统出现其它错误时，重定向到 vue 对应的错误页面
 * </pre>
 *
 * @author Kevin
 * @see org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
 */
public class CustomErrorViewResolver implements ErrorViewResolver {

    private static final ModelAndView FORBIDDEN_VIEW = new ModelAndView("redirect:/#/403");

    private static final Map<HttpStatus.Series, String> SERIES_VIEWS;

    static {
        var views = new EnumMap<HttpStatus.Series, String>(HttpStatus.Series.class);
        views.put(HttpStatus.Series.CLIENT_ERROR, "/#/404");
        views.put(HttpStatus.Series.SERVER_ERROR, "/#/500");
        SERIES_VIEWS = Collections.unmodifiableMap(views);
    }

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        if (status.value() == HttpStatus.FORBIDDEN.value()) {
            return FORBIDDEN_VIEW;
        }
        var view = SERIES_VIEWS.getOrDefault(status.series(), SERIES_VIEWS.get(HttpStatus.Series.SERVER_ERROR));
        return new ModelAndView(STR."redirect:\{view}");
    }
}
